package com.dapeis.service;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import com.ag.module.common.api.utils.qrcode.QrCodeUtils;
import com.ag.utils.DateUtils;
import com.ag.utils.NumberUtils;
import com.dapeis.core.utils.StringUtil;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Collocation;
import com.google.zxing.WriterException;

/**
 * 二维码
 * 
 * @author 作者 E-mail: hzyuanyong@126.com
 * @version 创建时间：2017年5月11日 下午2:13:20 类说明
 */

@Service
public class QRCodeService {

    @Resource
    COSFileService cosFileService;

    public String createCollocationQRCode(Collocation collocation,
	    HttpServletRequest request) {
	String url = "";
	if (StringUtil.isBlank(collocation.getQrCodeUrl())) {
	    String content = "/wx/qr?cid=" + collocation.getId();
	    url = creatseQRCode(content, request);
	} else {
	    // 存在返回
	    url = collocation.getQrCodeUrl();
	}
	return url;
    }

    /**
     * 生成二维码
     * 
     * @param content
     * @return
     * @throws IOException
     * @throws WriterException
     */
    String creatseQRCode(String content, HttpServletRequest request) {
	// 生成二维码文件
	String tmpPath = request.getRealPath("/") + "temp/";
	String tmpFileName = DateUtils.nowDate(DateUtils.YYYYMMDDHHMMSS)
		+ NumberUtils.random() + ".jpg";
	File localFile;
	String qrCodeUrl = "";
	try {
	    localFile = QrCodeUtils
		    .makeQRimgFile(content, tmpPath, tmpFileName);
	    qrCodeUrl = cosFileService.saveFile(localFile,
		    StylistConstants.UploadType.QRCODE);
	} catch (WriterException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return qrCodeUrl;
    }

}
